package everydayone.addTwoNumber;

import java.util.LinkedList;

import primaryAlgorithm.deleteNode.ListNode;

/**
 * @Date 2020/04/14
 * @author 王光浩
 * @Thinking 将 方法二中的代码进行优化
 */
public class MyMethodThree {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		LinkedList<Integer> stack1 = new LinkedList<Integer>();
		LinkedList<Integer> stack2 = new LinkedList<Integer>();
		// 将 l1 进行翻转
		while (l1 != null) {
			stack1.push(l1.val);
			l1 = l1.next;
		}
		// 将 l2 进行翻转
		while (l2 != null) {
			stack2.push(l2.val);
			l2 = l2.next;
		}
		// 将数字进行合并
		int overflow = 0;
		ListNode ret = null;
		while (!stack1.isEmpty() || !stack2.isEmpty() || overflow==1) {
			// 将两个节点相加的结果保存（注意溢出）
			int val1 = stack1.isEmpty()? 0 : stack1.pop();
			int val2 = stack2.isEmpty()? 0 : stack2.pop();
			int count = val1 + val2 + overflow;
			ListNode tem = new ListNode(count % 10);
			overflow = (count) >= 10 ? 1 : 0;
			tem.next = ret;
			ret = tem;
		}
		return ret;
	}
}
